<script setup lang="ts">
  import { transformContent } from '@nuxt/content/transformers'
  import { articleAPI } from '~/apis/article'
  import type { BlogPost } from '~/types'

  const route = useRoute()
  const articleId = route.params.articleId
  const { data } = await articleAPI.detail(Number(articleId))

  if (!data.value) {
    throw createError({ statusCode: 404, statusMessage: '未找到文章', fatal: true })
  }
  const p: Omit<BlogPost, '_id' | 'body'> = await transformContent(
    `${articleId}.md`,
    data.value.content
  )
  const post: BlogPost = transformPost(data.value, p)

  // 获取前后两篇文章
  const { data: adjacentArticles } = await articleAPI.getAdjacentArticles(Number(articleId))

  if (!adjacentArticles.value) {
    throw createError({ statusCode: 404, statusMessage: '未找到文章', fatal: true })
  }
  const prev = adjacentArticles.value.prevArticle
    ? transformPost(adjacentArticles.value.prevArticle, p)
    : null
  const next = adjacentArticles.value.nextArticle
    ? transformPost(adjacentArticles.value.nextArticle, p)
    : null
  const surround: any[] = prev || next ? [prev, next] : []

  useSeoMeta({
    title: post.title,
    ogTitle: post.title,
    description: post.description,
    ogDescription: post.description
  })
</script>

<template>
  <UContainer v-if="post">
    <UPageHeader :title="post.title" :description="post.description">
      <template #headline>
        <UBadge v-bind="post.badge" variant="subtle" />
        <span class="text-gray-500 dark:text-gray-400">&middot;</span>
        <time class="text-gray-500 dark:text-gray-400">{{
          new Date(post.date).toLocaleDateString()
        }}</time>
      </template>

      <div class="flex flex-wrap items-center gap-3 mt-4">
        <UButton
          v-for="(author, index) in post.authors"
          :key="index"
          :to="author.to"
          color="white"
          target="_blank"
          size="sm"
        >
          <UAvatar v-bind="author.avatar" :alt="author.name" size="2xs" />

          {{ author.name }}
        </UButton>
      </div>
    </UPageHeader>

    <UPage>
      <UPageBody prose>
        <ContentRenderer v-if="post && post.body" :value="post"></ContentRenderer>

        <hr v-if="surround?.length" />

        <UContentSurround :surround="surround" />
      </UPageBody>

      <template #right>
        <UContentToc v-if="post.body && post.body.toc" :links="post.body.toc.links" title="目录" />
      </template>
    </UPage>
  </UContainer>
</template>
